<?php
Yii::import('application.venders.*');
class PublishController extends Controller
{
	//发布某个商品的文章
	public function actionAdd(){
		$this->layout = '//layouts/main';
		$archiveForm = new Archives();
		$this->performAjaxValidation($archiveForm);
		if(isset($_POST['Archives']))
		{
			$data = $_POST['Archives'];
			$arctiny = new Arctiny;
			$arctiny->typeid = $data['typeid'];
			if($arctiny->validate()){
				$arctiny->save();
			}else{
				var_dump($arctiny->getErrors());
			}
			$archiveForm->id = $arctiny->attributes['id'];
			//上传图片 TODO
			$litpic = $this->uploadimg($data['litpic']);
			if(!$litpic){
				$upload = new Uploads;
				$upload->title = $data['title'];
				$upload->url = $litpic;
				$upload->filesize = filesize($litpic);
				if($upload->validate()){
					$upload->save();				
				}else{
					var_dump($upload->getErrors());
				}
			}
			$litpic = '/mall/'.$litpic;
			$archiveForm->attributes = $data;
			$archiveForm->litpic = $litpic;
			if($archiveForm->validate()){
				$archiveForm->save();
			}else{
				var_dump($archiveForm->getErrors());
			}
			if(isset($_POST['Addonarticle'])){
				$addonarticledata = $_POST['Addonarticle'];
				$addonarticle = new Addonarticle;
				$addonarticle->aid = $arctiny->attributes['id'];
				$addonarticle->typeid = $data['typeid'];
				$addonarticledata['body'] = preg_replace('/<img src="(.*?)"/','<img src="'.$litpic.'" ',$addonarticledata['body']);
				/*
				$type = Category::model()->find('id=:id',array(':id'=>(int)$data['typeid']));
				foreach(Yii::app()->params[$type->keyfile] as $key){
					$addonarticledata['body'] = preg_replace('/(.*[^(<a.*>)])('.$key[0].')(.*[^<\/a>])/','${1}<a target="_blank" href="'.$key[1].'">${2}</a>${3}',$addonarticledata['body']);
				}
				*/
				$addonarticle->attributes = $addonarticledata;
				$addonarticle->userip = $this->getUserIp();
				if($addonarticle->validate()){
					$addonarticle->save();
					
				}else{
					var_dump($addonarticle->getErrors());
				}
			}
			//插入tags
			$vowels = array(' ', '，');
			$tagstring = trim(str_replace($vowels,'',$data['keywords']),',');
			$tags = explode(',',$tagstring);
			Tagindex::model()->addAll($arctiny->attributes['id'],$data['typeid'],$tags);
			//发微博信息 TODO
			
			$this->redirect(array('items/admin'));
			Yii::app()->end();
			
		}
		$iid = trim($_GET['iid']);
		//item detail
		$newcfg = array(
			'method' => 'taobao.taobaoke.items.detail.get',
			'fields' => 'click_url,shop_click_url,pic_url,volume,seller_credit_score,nick,title,price,desc',
			'num_iids' => $iid,
			'outer_code' => 'miyifun',
		);

		$api = new TaobaoApi($newcfg);
		$result = $api->getSingleData();
		$detail = $result['taobaoke_items_detail_get_response']['taobaoke_item_details']['taobaoke_item_detail'];
		//var_dump($detail);
		if($detail){
			$item = new Items;
			$item->num_iid = $iid;
			$item->title = $detail[0]['item']['title'];
			$item->click_url = $detail[0]['click_url'];
			$item->shop_click_url = $detail[0]['shop_click_url'];
			$item->seller_credit_score = $detail[0]['seller_credit_score'];
			if($item->validate()){
				$item->save();
			}else{
				echo 'validate false';
				$errorflag = true;
				var_dump($item->getErrors());
			}
		}else{
			echo 'have no data!';
			$this->redirect(array('item/list'));
			Yii::app()->end();
		}
		//评论
		$commentcfg = array(
			'method' => 'taobao.traderates.search',
			'num_iid' => $iid,
			'seller_nick' =>$detail[0]['item']['nick'],
			'page_size' => 5,
			'outer_code' => 'miyifun',
		);
		$comapi = new TaobaoApi($commentcfg);
		$commentresult = $comapi->getSingleData();
		//var_dump($commentresult);
		
		$comments = $commentresult['traderates_search_response']['trade_rates']['trade_rate'];
		//var_dump($comments);
		if(count($comments)>0){
			if(!$errorflag){
				Comments::model()->addAll($iid,$comments);
			}
				$commentString =  '<h3 class="detailimg_title">最新用户评论</h3><div class="note-list"><ul class="pl_list">';
					foreach($comments as $key=>$comment){
						$commentString .= '<li class="list_info"><a class="img_face" href="" ><img class="namecard js_processed" alt="" src="http://www.jimeishuo.com/images/avatar-tao.png"></a><p><span class="cgray r">'.$comment['created'].'</span><span class="red">'.$comment['nick'].'</span></p><p class="tj">'.$comment['content'].'</p></li>';
					}
					$commentString .= '</ul></div>';
		}
		$commentresult['traderates_search_response']['total_results'] = $commentresult['traderates_search_response']['total_results'] >200 ? $commentresult['traderates_search_response']['total_results'] : rand(700,2000);
		$petten = array('&nbsp;','');
		$detail[0]['item']['desc'] = str_replace($petten,'',$detail[0]['item']['desc']);
		$imgcontent = '<div class="code_pic"><a href="http://www.jimeishuo.com/mall/direct/goto.html?iid='.$iid.'&frm=out_pic" target="_blank" rel="nofollow"><img src="'.$detail[0]['item']['pic_url'].'" alt="'.$detail[0]['item']['title'].'" /></a></div>';
		$imgcontent .= '<div class="goodsdetail"><div class="break-word"><p class="f14 l22"><a href="http://www.jimeishuo.com/mall/direct/goto.html?iid='.$iid.'&frm=out_pic" target="_blank"   rel="nofollow" class="goods_title">'.$detail[0]['item']['title'].'</a></p><p class="p12">价格:'.$detail[0]['item']['price'].'元</p><p><samp class="looklink red"><a href="http://www.jimeishuo.com/mall/direct/goto.html?iid='.$iid.'&frm=out_pic" target="_blank" rel="nofollow" >去淘宝网购买&gt;&gt;</a></samp></p><p class="p_heart"><a href="http://www.jimeishuo.com/mall/direct/goto.html?iid='.$iid.'&frm=out_pic" target="_blank" class="notlike_it cursor pop_comm" ><b class="red nums">'.$commentresult['traderates_search_response']['total_results'].'</b></a></p><a class="arrow_look mt14 cursor" href="http://www.jimeishuo.com/mall/direct/goshop.html?iid='.$iid.'&frm=out_pic" target="_blank" rel="nofollow" ><span class="left red">去 <span class="f16">'.$detail[0]['item']['nick'].'</span> 店里看更多</span><span class="f14 left goods_icon cdress cursor red">宝贝&gt;&gt;</span></a></div></div>';
		$body = $imgcontent.'<div class="clear"></div><div class="maincontent"><p>修改这里的内容'.$detail[0]['item']['desc'].'</p><p class="gotoshop"><a href="http://www.jimeishuo.com/mall/direct/goto.html?iid='.$iid.'&frm=out_pic" target="_blank" rel="nofollow" >去淘宝网购买&gt;&gt;</a></p></div>'.$commentString;
		$archiveForm->title = $detail[0]['item']['title'];
		$archiveForm->description = substr($detail[0]['item']['desc'],0,200);
		$archiveForm->litpic = $detail[0]['item']['pic_url'];
		
		$addonarticle = new Addonarticle();
		$addonarticle->body = $body;
		$this->render('add',array('detail'=>$detail,'body'=>$body,'formModel'=>$archiveForm,'addonarticle'=>$addonarticle));
	}
	/*
	*发送腾讯微博
	*/
	private function postTencentWeibo($text, $pic_path) {
		require_once("OpenSDK/Tencent/Weibo.php");
		OpenSDK_Tencent_Weibo::init(Yii::app()->params['OpenSDK']['Tencent']['Weibo']['key'], Yii::app()->params['OpenSDK']['Tencent']['Weibo']['secret']);
		$_SESSION[OpenSDK_Tencent_Weibo::ACCESS_TOKEN]= 'e2130b990e504b9d96a1449f70710c0c' ;
		$_SESSION[OpenSDK_Tencent_Weibo::OAUTH_TOKEN_SECRET] = '06a73599b905f0ab9199787f2c0b465c';
		
		return OpenSDK_Tencent_Weibo::call(
				't/add_pic',
				array(
						'content' => $text,
						'clientip' => $_SERVER["REMOTE_ADDR"]
				),
				'POST',
				array('pic' => $pic_path)
		);
	}
	/*
	*发送腾讯微博
	*/
	private function postSinaWeibo($text, $pic_path) {
		require_once 'OpenSDK/Sina/Weibo.php';
		OpenSDK_Sina_Weibo::init(Yii::app()->params['OpenSDK']['Sina']['Weibo']['key'], Yii::app()->params['OpenSDK']['Sina']['Weibo']['secret']);
		$_SESSION[OpenSDK_Sina_Weibo::ACCESS_TOKEN]= 'e2130b990e504b9d96a1449f70710c0c' ;
		$_SESSION[OpenSDK_Sina_Weibo::OAUTH_TOKEN_SECRET] = '06a73599b905f0ab9199787f2c0b465c';
		
		return OpenSDK_Sina_Weibo::call(
				't/add_pic',
				array(
						'content' => $text,
						'clientip' => $_SERVER["REMOTE_ADDR"]
				),
				'POST',
				array('pic' => $pic_path)
		);
	}
	/**
	*根据图片url 上传图片
	*/
	public function uploadimg($imgurl=''){
		$url = parse_url($imgurl);
		$host = $_SERVER['HTTP_HOST'];
		if(isset($url['host']) && $url['host'] != $host) {
			$path = $url['path'];
			if(!empty($url['query'])) {
				$path .= '?' . $url['query'];
			}
			$http_request = "GET $path HTTP/1.0\r\n";
  			$http_request .= "ACCEPT: */*\r\n";
  			$http_request .= "ACCEPT-LANGUAGE: zh-cn\r\n";
  			$http_request .= "USER_AGENT: ".$_SERVER['HTTP_USER_AGENT']."\r\n";
  			$http_request .= "HOST: ".$url['host']."\r\n";
  			$http_request .= "CONNECTION: close\r\n";
  			$http_request .= "COOKIE: $_COOKIE\r\n\r\n";
  			$response = '';
			if(FALSE != ($fs = @fsockopen($url['host'], empty($url['port']) ? 80 : $url['port'], $errno, $errstr, 10))) {
				fwrite($fs, $http_request);
				while (!feof($fs)) {
					$response .= fgets($fs, 1160);
				}
				fclose($fs);
				$response = explode("\r\n\r\n", $response, 2);
				$imgData = $response[1];
				preg_match("/Content-Type: (.*)\r\n/i",$response[0],$imgType);
				$imgType = $imgType[1];
				$imgExt  = strtolower(substr(strrchr($imgurl, "."),1));
				if(empty($imgExt)) {
					if($imgType == 'image/pjpeg' || $imgType == 'image/jpeg') {
						$imgExt = 'jpg';
					} elseif ($imgType == 'image/x-png' || $imgType == 'image/png') {
						$imgExt = 'png';
					} elseif ($imgType == 'image/gif') {
						$imgExt = 'gif';
					} elseif ($imgType == 'image/bmp') {
						$imgExt = 'bmp';
					} else {
						$imgExt = 'jpg';
					}
				}
				$uppath = 'uploads/'.date('Ym',time());
				$fname = md5($imgName) . gmdate('YmdHis') .'.'. $imgExt;
				$attachpath = $uppath .'/'. $fname;
				if (!is_dir($uppath)){
					umask(0);
					$ret = @mkdir($uppath, 0777);
					if ($ret === false){
						echo '文件上传目录uploads不可写';
					}
				}
				if($fp = @fopen($attachpath,'w')) {
					fwrite($fp,$imgData);
					return $attachpath;
				} else {
					echo'图片文件写入失败';
				}
			}	
		}
		return false;
	}
	
	/**
	 * Suggests tags based on the current user input.
	 * This is called via AJAX when the user is entering the tags input.
	 */
	public function actionSuggestTags()
	{
		if(isset($_GET['q']) && ($keyword=trim($_GET['q']))!=='')
		{
			$tags=Tagindex::model()->suggestTags($keyword);
			if($tags!==array())
				echo implode("\n",$tags);
		}
	}
	public function accessRules(){
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('suggestTags','uploadimg'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('add','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','add','update'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	
	}
	/*获得用户的ip地址
	*/
	public function getUserIp(){
		static $realip = NULL;
        if ($realip !== NULL)
        {
            return $realip;
        }
        if (isset($_SERVER))
        {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                /* 取X-Forwarded-For中第x个非unknown的有效IP字符? */
                foreach ($arr as $ip)
                {
                    $ip = trim($ip);
                    if ($ip != 'unknown')
                    {
                        $realip = $ip;
                        break;
                    }
                }
            }elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            }else{
                if (isset($_SERVER['REMOTE_ADDR']))
                {
                    $realip = $_SERVER['REMOTE_ADDR'];
                }
                else
                {
                    $realip = '0.0.0.0';
                }
            }
        }else{
            if (getenv('HTTP_X_FORWARDED_FOR'))
            {
                $realip = getenv('HTTP_X_FORWARDED_FOR');
            }
            elseif (getenv('HTTP_CLIENT_IP'))
            {
                $realip = getenv('HTTP_CLIENT_IP');
            }
            else
            {
                $realip = getenv('REMOTE_ADDR');
            }
        }
        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        $realip = ! empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
        return $realip;
	}
	
	public function filters()
	{
		return array(
			'accessControl',
		);
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model= Article::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
   /**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='articleform')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}